package org.ellisande.grid.tags.support;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class TagBuilder {
	private Map<String, String> attributes;
	private List<String> styles;

	private String tagName;

	private static String TAG_OPEN_START = "<";
	private static String TAG_OPEN_END = ">";
	private static String TAG_CLOSE_START = "</";
	private static String TAG_CLOSE_END = ">";
	private static String SEPERATOR = " ";
	private static String ATTRIBUTE_START = "=\"";
	private static String ATTRIBUTE_END = "\"";

	public TagBuilder(String name) {
		this.tagName = name;
		attributes = Collections.synchronizedMap(new HashMap<String, String>());
		styles = new ArrayList<String>();
	}

	public void addAttribute(String attribute, String value) {
		attributes.put(attribute, value);
	}

	public void addStyle(String style) {
		styles.add(style);
	}

	public void addStyles(String styles) {
		String[] splitStyles = styles.split("\\s");
		this.styles.addAll(Arrays.asList(splitStyles));
	}

	private String getCompiledStyles() {
		StringBuilder builder = new StringBuilder();
		for (String style : styles) {
			builder.append(style + SEPERATOR);
		}
		return builder.toString();
	}

	public String compileStartTag() {
		StringBuilder tag = new StringBuilder();
		tag.append(TAG_OPEN_START);
		tag.append(tagName + SEPERATOR);

		if (!styles.isEmpty()) {
			addAttribute("class", getCompiledStyles());
		}

		for (Map.Entry<String, String> entry : attributes.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			tag.append(key);
			tag.append(ATTRIBUTE_START);
			tag.append(value);
			tag.append(ATTRIBUTE_END);
			tag.append(SEPERATOR);
		}

		tag.append(TAG_OPEN_END);

		return tag.toString();
	}

	public String compileEndTag() {
		return TAG_CLOSE_START + tagName + TAG_CLOSE_END;
	}

}
